#include "searchwig.h"
#include "ui_searchwig.h"
#include <QNetworkInterface>


searchwig::searchwig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::searchwig)
{
    ui->setupUi(this);
    ui->online_button->setStyleSheet("QPushButton {background: transparent;background-color: rgba(255, 255, 255, 50); color:white;}");
    ui->search_button->setStyleSheet("QPushButton {background: transparent;background-color: rgba(255, 255, 255, 50); color:white;}");
    ui->ota_button->setStyleSheet("QPushButton {background: transparent;background-color: rgba(255, 255, 255, 50); color:white;}");
    ui->online_edit->setStyleSheet("QTextEdit {background-color: rgba(255, 255, 255, 50);border: 1px solid rgba(0, 0, 0, 30); color:white;}");
    ui->search_edit->setStyleSheet("QTextEdit {background-color: rgba(255, 255, 255, 50);border: 1px solid rgba(0, 0, 0, 30); color:white;}");
    ui->ota_button->setEnabled(false);
    ui->ota_button->setStyleSheet("background-color: rgba(128, 128, 128, 150);");

    tcpSocket = new QTcpSocket(this);
    udpSocket = new QUdpSocket(this);

    connect(udpSocket,&QUdpSocket::readyRead,this,&searchwig::processUdpResponse);
    connect(tcpSocket,&QTcpSocket::readyRead,this,&searchwig::readTcpData);
    connect(this,&searchwig::UpdateStatus,this,&searchwig::handleStatus);
}

searchwig::~searchwig()
{
    delete ui;
    if(tcpSocket->isOpen())
    {
        tcpSocket->disconnectFromHost();
    }
    udpSocket->close();
    delete udpSocket;
}


void searchwig::sendDiscoveryBroadcast()
{
    // 发送UDP广播
    QByteArray datagram = "DEVICE_DISCOVERY";
    quint16 udpPort = 9999;

    // 获取所有网络接口
    QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
    foreach (const QNetworkInterface &interface, interfaces)
    {
        // 只处理活动的、非回环的、支持广播的接口
        if ((interface.flags() & QNetworkInterface::IsUp)
                &&(interface.flags() & QNetworkInterface::IsRunning)
                &&!(interface.flags() & QNetworkInterface::IsLoopBack)
                &&(interface.flags() & QNetworkInterface::CanBroadcast))
        {

            // 获取接口的所有IP地址
            QList<QNetworkAddressEntry> entries = interface.addressEntries();
            foreach (const QNetworkAddressEntry &entry, entries)
            {
                // 只处理IPv4地址
                if (!entry.broadcast().isNull() && entry.ip().protocol() == QAbstractSocket::IPv4Protocol)
                {
                    // 发送广播
                    udpSocket->writeDatagram(datagram, entry.broadcast(), udpPort);
                    //ui->search_edit->append("发送发现广播到: " + entry.broadcast().toString());
                }
            }
        }
    }

}


void searchwig::processUdpResponse()
{
    while (udpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

        QString response = QString::fromUtf8(datagram);
        //ui->search_edit->append("收到UDP响应: " + response + " 来自 " + sender.toString() + ":" + QString::number(senderPort));

        // 解析响应
        if (response.startsWith("DEVICE_RESPONSE:"))
        {
            QStringList parts = response.split(":");
            if (parts.size() == 3)
            {
                QString ip = parts[1];
                quint16 port = parts[2].toUShort();

                ui->search_edit->append("发现设备: IP=" + ip + ", 端口=" + QString::number(port));

                // 连接到TCP服务器
                connectToTcpServer(ip, port);
                return; // 只处理第一个响应
            }
        }
    }
}


void searchwig::connectToTcpServer(const QString &ip, quint16 port)
{
    if(tcpSocket->state() == QAbstractSocket::ConnectedState)
    {
        tcpSocket->disconnectFromHost();
        ui->search_edit->append("断开连接...");
        return;
    }

    ui->search_edit->append("正在连接服务器 " + ip + ":" + QString::number(port) + "...");
    tcpSocket->connectToHost(ip, port);

    if(tcpSocket->waitForConnected(1000))
    {
        ui->search_edit->append("连接成功...");
        emit IpSignal(ip);
        ui->ota_button->setEnabled(true);
        ui->ota_button->setStyleSheet("QPushButton {background: transparent;background-color: rgba(255, 255, 255, 50); color:white;}");
        tcpSocket->write("Q");
    }
    else
    {
        ui->search_edit->append("连接失败: " + tcpSocket->errorString());
    }
}


void searchwig::on_search_button_clicked()
{
    // 先发送UDP广播发现设备
    sendDiscoveryBroadcast();
    ui->search_edit->append("正在搜索设备...");
}


void searchwig::on_online_button_clicked()
{
    if(tcpSocket->state() == QAbstractSocket::ConnectedState)
    {
        // 请求状态更新
        tcpSocket->write("CHECK_STATUS");
    }
    else
    {
        ui->online_edit->setText("未连接到服务器");
    }
}

void searchwig::readTcpData()
{
    QByteArray data = tcpSocket->readAll();
    QString msg = QString::fromUtf8(data);

    if(msg == "{\"ONLINE\":1}")
    {
        emit UpdateStatus("设备在线");
    }
    else
    {
        emit UpdateStatus("设备不在线");
    }
}

void searchwig::handleStatus(const QString &status)
{
    ui->online_edit->setText(status);
    ui->online_edit->setAlignment(Qt::AlignCenter);

    // 根据状态设置不同颜色
    if(status == "设备在线") {
        ui->online_edit->setStyleSheet("color: green; background-color: rgba(255, 255, 255, 50);");
    } else {
        ui->online_edit->setStyleSheet("color: red; background-color: rgba(255, 255, 255, 50);");
    }
}
